
import 'dart:convert';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';

import 'result_data.dart';

class RequestInterceptors extends InterceptorsWrapper {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    var timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    String domain = "linkseed.io";
    var signature = EncryptUtil.encodeMd5('$timestamp${domain}DANARAJA');

    options.headers.addAll({
      'timestamp': timestamp,
      'domain': domain,
      'signature': signature,
      'orgId': 'smart_card_pro',
    });
    print('headers:${jsonEncode(options.headers)}');
    return super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    RequestOptions option = response.requestOptions;
    print('${option.path} http end <- ${response.data}');
    Map<String, dynamic> data;
    if (response.data is String) {
      data = json.decode(response.data);
    } else {
      data = response.data;
    }

    var code = data["errcode"];
    if (code == '0') {
      handler.resolve(Response(
          data: ResultData(true, int.parse(code), '', data: data['data']),
          requestOptions: option));
    }else {
      handler.resolve(Response(
          data: _getErrorMessage(int.parse(code)), requestOptions: option));
      handler.resolve(Response(
          data: ResultData(false, int.parse(code), data['errmsg'], data: data),
          requestOptions: option));
    }
  }

  ResultData _getErrorMessage(int code) {
    if (code == 1001) {
      return ResultData(false, code,
          'Remote server or network failed, Please try again later.');
    } else if (code == 40108) {
      return ResultData(false, code, 'No customer exist');
    } else if (code == 40112) {
      return ResultData(false, code, 'Incorrect password');
    } else {
      return ResultData(false, code, 'Unknow error');
    }
  }
}
